import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { BaseException } from './base.exception';
import { BusinessException } from './business.exception';

/**
 * 全局异常过滤器
 * 基于 NestJS 异常处理实现
 * 参考: https://docs.nestjs.cn/exception-filters
 * 对应 Java: GlobalExceptionHandler
 */
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(GlobalExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let status: number;
    let errorResponse: any;

    if (exception instanceof BaseException) {
      // 自定义业务异常
      status = exception.statusCode;
      errorResponse = exception.toResponse();
      errorResponse.error.path = request.url;
    } else if (exception instanceof HttpException) {
      // NestJS HTTP 异常
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      if (typeof exceptionResponse === 'string') {
        errorResponse = {
          success: false,
          error: {
            code: 'HTTP_ERROR',
            message: exceptionResponse,
            statusCode: status,
            timestamp: new Date().toISOString(),
            path: request.url,
          },
        };
      } else {
        errorResponse = {
          success: false,
          error: {
            code: 'HTTP_ERROR',
            message: (exceptionResponse as any).message || 'HTTP异常',
            statusCode: status,
            timestamp: new Date().toISOString(),
            path: request.url,
            details: exceptionResponse,
          },
        };
      }
    } else {
      // 未知异常
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      errorResponse = {
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: '系统内部错误',
          statusCode: status,
          timestamp: new Date().toISOString(),
          path: request.url,
        },
      };
    }

    // 记录错误日志
    this.logger.error(
      `Exception caught: ${exception instanceof Error ? exception.message : 'Unknown error'}`,
      exception instanceof Error ? exception.stack : undefined,
      {
        url: request.url,
        method: request.method,
        ip: request.ip,
        userAgent: request.get('User-Agent'),
        status,
        errorCode: errorResponse.error.code,
      },
    );

    // 发送响应
    response.status(status).json(errorResponse);
  }
}
